import fs from "fs-extra";
import path from "path";

export class Hudson {
    public static getHudsonHome(): string {
        // D:\tomcat\webapps\hudson
        return process.env.HUDSON_HOME || '' ;
    }
    
    public static getBuildNumber(): string {
        // 173
        return process.env.BUILD_NUMBER || '' ;
    }
    
    public static getBuildID(): string {
        // 2023-07-05_11-11-45
        return process.env.BUILD_ID || '' ;
    }
    
    public static getBuildURL(): string {
        // metrofee/job/%E7%9C%9F%E7%BA%A2%E4%B9%8B%E5%88%83-develop/173/
        return process.env.BUILD_URL || '' ;
    }
    
    public static getJobName(): string {
        // 真红之刃-develop
        return process.env.JOB_NAME || '' ;
    }

    public static getJobWorkSpace(buildID: string): string {
        return path.join(Hudson.getHudsonHome(), 'jobs', Hudson.getJobName(), 'builds', buildID);
    }

    public static async getStartUser(): Promise<string> {
        let user = '';
        // 获取日志
        const jobWs = this.getJobWorkSpace(Hudson.getBuildID());
        const logFile = path.join(jobWs, 'log');
        if (fs.existsSync(logFile)) {
            const logContent = await fs.readFile(logFile, 'utf-8');
            if (logContent.includes('Started by timer')) {
                user = '~';
            } else {
                const mch = logContent.match(/(?<=Started by user )\S+/);
                if (mch != null) {
                    user = mch[0];
                    console.log('get start user sucessfully:', user);
                } else {
                    console.error('cannot tell authenticated user, log content:');
                    console.log('----------');
                    console.log(logContent);
                    console.log('----------');
                }
            }
        } else {
            console.error('cannot tell authenticated user cause log file not exists:', logFile);
        }
        return user;
    }

    public static async isSupportRebuild(): Promise<boolean> {
        // 检查是否支持Rebuild参数
        const cfgXml = path.join(Hudson.getHudsonHome(), 'jobs', Hudson.getJobName(), 'config.xml');
        if (fs.existsSync(cfgXml)) {
            const cfgContent = await fs.readFile(cfgXml, 'utf-8');
            if (cfgContent.includes('<name>Rebuild</name>')) {
                return true;
            }
        }
        return false;
    }

    public static getLogUrl() {
        return `http://builder.fygame.com:8282/hudson/job/${Hudson.getJobName()}/${Hudson.getBuildNumber()}/consoleText`;
    }
}
